






<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Chapter 5 Continued: JNI Example</title>
<meta name="collection" content="learning">
<meta name="keywords" content="programming, advanced, Java, 2">
<meta name="description" content="Advanced Programming for the Java 2 Platform. This section presents the ReadFile example program, showing how you can use the Java Native Interface (JNI) to invoke a native method that makes C function calls to map a file into memory.">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta name="archive" content="false">
<meta name="date" content="2003-03-22">
<link rel="stylesheet" href="/css/default_developer.css" />


<script type="text/javascript" language="JavaScript" src="/js/popUp.js"></script>
<script language="javascript1.2" type="text/javascript" src="/js/sniff.js"></script>
<script language="javascript1.2" type="text/javascript" src="/js/menucontent.js"></script>
<script language="javascript1.2" type="text/javascript" src="/js/menucode.js"></script>
<script language="javascript1.2" type="text/javascript" src="/js/developer.js"></script>


</head>
<!--stopindex-->
<body leftmargin="0" topmargin="0" marginheight="0" marginwidth="0" rightmargin="0" bgcolor="#ffffff" onload="prepmenus(); done=true">

<a name="top"></a>
<!-- BEGIN GENERIC MASTHEAD -->


<!-- BEGIN A1 COMPONENT V.0 -->
<div class="a1 a1r2">
<div class="a1v0">
<a href="#skip2content" class="skiplink">Skip to Content</a>
<span class="toolbarlinks">
<a href="/global/mh/suncom/index.html">Sun</a>
<a href="/global/mh/java/">Java</a>
<a href="/global/mh/solaris/">Solaris</a>
<a href="/global/mh/communities/" class="dividelink">Communities</a>
<a href="http://developers.sun.com/global/my_profile.html">My SDN Account</a>

</span>
</div>
</div>
<!-- END A1 COMPONENT V.0 -->

<!-- BEGIN A2 COMPONENT V.1 -->
<div class="a2w0">
<div class="a2" id="a2v1">
<div class="a2w1"><div class="a2w2"><div class="a2w3"><div class="a2w4">
<div class="a2topiclinks">
<div class="a2search">
<form action="http://search.sun.com/main/index.jsp" accept-charset="utf-8" method="GET">
<input type="hidden" name="charset" value="utf-8">
<input type="hidden" name="col" value="main-developer-all">
<span class="rightarrowwhite">&raquo;</span>&nbsp;<a href="http://developers.sun.com/global/search_tips.html">search tips</a>&nbsp;
<input class="searchfield" name="qt" class="medium" size="7" onFocus="if( this.value==this.defaultValue ) this.value='';" value="Search">
<input id="searchbttn" type="image" border="0" src="/im/a2_bttn_search.gif" alt="Submit Search">
</form>
</div>
<a href="http://www.sun.com" title="Home Page" id="sunlogo"><img src="/im/a.gif" alt="Home Page" width="98" height="58" border="0" /></a>
<a href="http://developers.sun.com" title="Sun Developer Network"><img src="/im/a.gif" id="venuespacer" alt="Sun Developer Network" width="400" height="33" border="0" /></a>
<ul id="mtopics">
<li id="mtopic1"><a id="glink1" class="tpclink a2menu" title="See All APIs" href="/global/mh/api/index.html">APIs</a></li>
<li id="mtopic2"><a id="glink2" class="tpclink a2menu" title="See All Downloads" href="/global/mh/downloads/index.html">Downloads</a></li>
<li id="mtopic3"><a id="glink3" class="tpclink a2menu" title="See All Products" href="/global/mh/products/index.html">Products</a></li>
<li id="mtopic4"><a id="glink4" class="tpclink a2menu" title="See All Support" href="/global/mh/support/index.html">Support</a></li>
<li id="mtopic5"><a id="glink5" class="tpclink a2menu" title="See All Training" href="/global/mh/training/index.html">Training</a></li>
<li id="mtopic6"><a id="glink6" class="tpclink a2menu" title="See All Participate" href="/global/mh/participate/index.html">Participate</a></li>
</ul>
</div>
</div></div></div></div>
</div></div>
<!-- END A2 COMPONENT V.1 -->









<!-- END GENERIC MASTHEAD -->
<!-- BEGIN BREADCRUMB -->
<table border="0" cellpadding="0" cellspacing="0" width="100%" class="vatop">
<tr>
<td>      
<div class="breadcrumb">
<a href="http://developers.sun.com/">SDN Home</a>
 &gt; <a href="http://developers.sun.com/prodtech/index.html">Products & Technologies</a> &gt; <a href="http://java.sun.com/index.jsp">Java Technology</a> &gt; <a href="http://java.sun.com/learning/index.html">Learning</a> &gt; <a href="http://java.sun.com/learning/tutorial/index.html">Tutorials and Code Camps</a> &gt; <a href="http://java.sun.com/developer/onlineTraining/Programming/JDCBook/index.html">Advanced Programming for the Java 2 Platform</a> &gt;
</div>
</td>
<td align="right" nowrap="nowrap"><div class="breadcrumb">
</div></td></tr>
<tr><td colspan="2"><img src="/im/a.gif" width="770" height="1" border="0" alt=" " /></td></tr>
</table>
<span class="sp5">&nbsp;</span><br />     
<!-- END BREADCRUMB -->
<!-- BEGIN PAGETITLE -->
<div class="pagetitle2">Tutorials & Code Camps</div>
<div class="smallpagetitle"><h1>Chapter 5 Continued: JNI Example</h1></div>
<!-- END PAGETITLE -->
<!-- BEGIN WRAPPER TABLE, 2 COLUMN, MAIN/RIGHT -->
<table border="0" cellpadding="10" cellspacing="0" width="100%">
<tr><td width="100%" valign="top">
<!-- BEGIN CENTRAL COLUMN COMPONENTS -->
<!--startindex-->
<!-- ============ -->
<!-- MAIN CONTENT -->
<!-- ============ -->
<a name="skip2content"></a>
<!--  BEGIN VCD4 PFV  -->
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td class="smaller" valign="top"><em></em></td>
<td width="10">&nbsp;</td>
<td align="right" valign="bottom"><div class="sitelinks" style="padding:0px;">
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td valign="bottom" align="right">&nbsp;</td>
<td valign="bottom" class="smaller" nowrap="nowrap"><a href="/jsp_utils/PrintPage.jsp" target="printFriendlyView" onclick="openPopup('','printFriendlyView',710,650,'no',1,1,0,0,0,0); return true;"><img src="/im/ic_print.gif" width="14" height="12" alt="Print-friendly Version" border="0" hspace="4" />Print-friendly Version</a><br></td>
</tr></table></div>
</td></tr>
</table>
<!--  END VCD4 PFV -->
<!-- ================== -->
<!-- Start Main Content -->
<!-- ================== -->
<a name="top"></a>
<a href="/developer/onlineTraining/index.html">Training Index</a>
<p>
</p>
<p>
[<a href="/developer/onlineTraining/Programming/JDCBook/jni.html">&lt;&lt;BACK</a>] [<a href="/developer/onlineTraining/Programming/JDCBook/index.html#contents">CONTENTS</a>] [<a href="/developer/onlineTraining/Programming/JDCBook/jnistring.html">NEXT&gt;&gt;</a>]
</p>
<p>
This section presents the <code>ReadFile</code> example program.
This example shows how you can use the Java Native Interface (JNI) to 
invoke a native method that makes C function calls to map a file into 
memory.  
</p>
<ul>
<li>
<a href="#examp">About the Example</a></font>
<ul>
<li>
<a href="#native">Native Method Declaration</a></font>
<li>
<a href="#load">Load the Library</a></font>
<li>
<a href="#comp">Compile the Program</a></font>
</ul>
<li>
<a href="#gen">Generate the Header File</a></font>
<li>
<a href="#sig">Method Signature</a></font>
<li>
<a href="#impl">Implement the Native Method</a></font>
<li>
<a href="#sol">Compile the Dynamic or Shared Object Library</a></font>
<li>
<a href="#run">Run the Example</a></font>
</ul>
<!-- BEGIN FRAGMENT | HR TAG -->
<div class="contentdivider"><table border="0" cellpadding="0" cellspacing="0" width="100%" class="grey4"><tr><td><img src="/im/a.gif" width="1" height="4" border="0" alt=" " /></td></tr></table></div>
<!-- END FRAGMENT | HR TAG -->
<a name="examp"></a>
<p>
<b>
About the Example</b>
</p>
<p>
You can call code written in any programming language from a program
written in the Java language by declaring a native Java method, loading 
the library that contains the native code, and then calling the native method. The
<code>ReadFile</code> source code below does exactly this.
</p>
<p>
However, successfully running the program requires a few additional steps beyond 
compiling the Java language source file. After you compile, but before you run the 
example, you have to generate a header file. The native code implements the function 
defintions contained in the generated header file and implements the business logic 
as well. The following sections walk through all the steps. 
</p>
<!-- BEGIN VCD7 CODE SAMPLE COMPONENT  -->
<table border="0" cellpadding="10" cellspacing="0" width="100%" class="grey4">
<tr><td><pre>
import java.util.*;

class ReadFile {
//Native method declaration
  native byte[] loadFile(String name);
//Load the library
  static {
    System.loadLibrary("nativelib");
  }

  public static void main(String args[]) {
    byte buf[];
//Create class instance
    ReadFile mappedFile=new ReadFile();
//Call native method to load ReadFile.java
    buf=mappedFile.loadFile("ReadFile.java");
//Print contents of ReadFile.java
    for(int i=0;i&lt;buf.length;i++) {
      System.out.print((char)buf[i]);
    }
  }
}
</pre></td></tr></table>
<span class="sp20"> </span><br />
<!-- END VCD7 CODE SAMPLE COMPONENT  -->
<a name="native"></a>
<p>
<b>Native Method Declaration</b>
</p>
<p>
The <code>native</code> declaration provides the bridge to run the native 
function in the Java<a href="#TJVM"><sup>1</sup></a> virtual machine. In this example, the 
<code>loadFile</code> function maps onto a C function called
<code>Java_ReadFile_loadFile</code>. The function implementation
accepts a <code>String</code> that represents a file name and returns the 
contents of that file in the byte array. 
<pre>
  native byte[] loadFile(String name);
</pre>
<a name="load"></a>
<p>
<b>Load the Library</b>
</p>
<p>
The library containing the native code implementation is loaded
by a call to <code>System.loadLibrary()</code>. Placing this
call in a static initializer ensures this library is only
loaded once per class. The library can be loaded outside of the 
static block if your application requires it. You might need to
configure your environment so the <code>loadLibrary</code> method
can find your native code library.
</p>
<pre>
  static {
    System.loadLibrary("nativelib");
  }
</pre>
<a name="comp"></a>
<p>
<b>Compile the Program</b>
</p>
<p>
To compile the program, just run the <code>javac</code> compiler
command as you normally would:
</p>
<pre>
  javac ReadFile.java
</pre>
<p>
Next, you need to generate
a header file with the native method declaration and implement
the native method to call the C functions for loading
and reading a file.
</p>
<a name="gen"></a>
<p>
<b>
Generate the Header File</b>
</p>
<p>
To generate a a header file, run the <code>javah</code> command on
the <code>ReadFile</code> class. In this example, the generated
header file is named <code>ReadFile.h</code>. It provides a method
signature that you have to use when you
implement the <code>loadfile</code> native function.
</p>
<pre>
  javah -jni ReadFile
</pre>
<p>
<blockquote>
<b>Note:</b>
When running <code>javah</code> on your own classes, be sure to use
the fully-qualified class name.
</blockquote>
<a name="sig"></a>
<p>
<b>
Method Signature</b>
</p>
<p>
The <code>ReadFile.h</code> header file defines the interface to map the
Java language method to the native C function. It uses a method signature to
map the arguments and return value of the Java language 
<code>mappedfile.loadFile</code> method to the <code>loadFile</code> native 
method in the <code>nativelib</code> library. Here is the 
<code>loadFile</code> native method mapping (method signature): 
</p>
<!-- BEGIN VCD7 CODE SAMPLE COMPONENT  -->
<table border="0" cellpadding="10" cellspacing="0" width="100%" class="grey4">
<tr><td><pre>
  /*
   * Class:     ReadFile
   * Method:    loadFile
   * Signature: (Ljava/lang/String;)[B
   */
  JNIEXPORT jbyteArray JNICALL Java_ReadFile_loadFile
    (JNIEnv *, jobject, jstring);
</pre></td></tr></table>
<span class="sp20"> </span><br />
<!-- END VCD7 CODE SAMPLE COMPONENT  -->
<p>
The method signature parameters function as follows:
</p>
<ul>
<li><code>JNIEnv *</code>: A pointer to the JNI environment. 
This pointer is a handle to the current thread in the Java virtual
machine, and 
contains mapping and other hosuekeeping information.
<p>
<li><code>jobject</code>:  A reference to the method that
called this native code. If the calling method is static, this parameter would
be type <code>jclass</code> instead of <code>jobject</code>.
<p>
<li><code>jstring</code>: The parameter supplied to the native method.
In this example, it is the name of the file to be read.  
</ul>
<a name="impl"></a>
<p>
<b>
Implement the Native Method</b>
</p>
<p>
In this native C source file, the <code>loadFile</code> definition is a 
copy and paste of the C declaration contained in <code>ReadFile.h</code>.
The definition is followed by the native method implementation.
JNI provides a mapping for both C and C++ by default.
</p>
<!-- BEGIN VCD7 CODE SAMPLE COMPONENT  -->
<table border="0" cellpadding="10" cellspacing="0" width="100%" class="grey4">
<tr><td><pre>
#include &lt;jni.h&gt;
#include &lt;sys/types.h&gt;
#include &lt;sys/ipc.h&gt;
#include &lt;sys/shm.h&gt;
#include &lt;sys/mman.h&gt;
#include &lt;sys/stat.h&gt;
#include &lt;fcntl.h&gt;
#include &lt;unistd.h&gt;

JNIEXPORT jbyteArray JNICALL Java_ReadFile_loadFile
  (JNIEnv * env, jobject jobj, jstring name) {
    caddr_t m;
    jbyteArray jb;
    jboolean iscopy;
    struct stat finfo;
    const char *mfile = (*env)-&gt;GetStringUTFChars(
                env, name, &amp;iscopy);
    int fd = open(mfile, O_RDONLY);

    if (fd == -1) {
      printf("Could not open %s\n", mfile);
    }
    lstat(mfile, &amp;finfo);
    m = mmap((caddr_t) 0, finfo.st_size,
                PROT_READ, MAP_PRIVATE, fd, 0);
    if (m == (caddr_t)-1) {
      printf("Could not mmap %s\n", mfile);
      return(0);
    }
    jb=(*env)-&gt;NewByteArray(env, finfo.st_size);
    (*env)-&gt;SetByteArrayRegion(env, jb, 0, 
	finfo.st_size, (jbyte *)m);
    close(fd);
    (*env)-&gt;ReleaseStringUTFChars(env, name, mfile);
    return (jb);
}
</pre></td></tr></table>
<span class="sp20"> </span><br />
<!-- END VCD7 CODE SAMPLE COMPONENT  -->
<p>
You can approach calling an existing C function instead of implementing one,
in one of two ways:  
</p>
<ol>
<li>Map the name generated by JNI to the existing C function name.
The <a href="/developer/onlineTraining/Programming/JDCBook/jniref.html#add">Language Issues</a>
section shows how to map between Xbase database functions and Java language code
<p>
<li>Use the shared stubs code available from the 
<a href="/products/jdk/faq/jnifaq.html">JNI page</a> 
on the java.sun.com web site.
</ol>
<a name="sol"></a>
<p>
<b>
Compile the Dynamic or Shared Object Library</b>
</p>
<p>
The library needs to be compiled as a dynamic or shared object library
so it can be loaded at runtime. Static 
or archive libraries are compiled into an executable and cannot be loaded 
at runtime.  The shared object or dynamic library for the
<code>loadFile</code> example is compiled as follows:
</p>
<!-- BEGIN VCD7 CODE SAMPLE COMPONENT  -->
<table border="0" cellpadding="10" cellspacing="0" width="100%" class="grey4">
<tr><td><pre>
<strong>Gnu C/Linux:</strong>

gcc  -o libnativelib.so -shared -Wl,-soname,libnative.so  
     -I/export/home/jdk1.2/include 
     -I/export/home/jdk1.2/include/linux nativelib.c  
     -static -lc

Gnu C++/Linux with Xbase

g++ -o libdbmaplib.so -shared -Wl,-soname,libdbmap.so  
    -I/export/home/jdk1.2/include 
    -I/export/home/jdk1.2/include/linux 
    dbmaplib.cc -static -lc -lxbase


<strong>Win32/WinNT/Win2000</strong>

cl -Ic:/jdk1.2/include 
   -Ic:/jdk1.2/include/win32 
   -LD nativelib.c -Felibnative.dll
</pre></td></tr></table>
<span class="sp20"> </span><br />
<!-- END VCD7 CODE SAMPLE COMPONENT  -->
<a name="run"></a>
<p>
<b>
Run the Example</b>
</p>
<p>
To run the example, the Java virtual machine needs to be able to find
the native library. To do this, set the library path to the
current directory as follows:
</p>
<p>
<!-- BEGIN VCD7 CODE SAMPLE COMPONENT  -->
<table border="0" cellpadding="10" cellspacing="0" width="100%" class="grey4">
<tr><td><pre>
<strong>Unix or Linux:</strong>
  LD_LIBRARY_PATH=`pwd`
  export LD_LIBRARY_PATH


<strong>Windows NT/2000/95:</strong>
  set PATH=%path%;.
</pre></td></tr></table>
<span class="sp20"> </span><br />
<!-- END VCD7 CODE SAMPLE COMPONENT  -->
<p>
With the library path properly specified for your platform, 
invoke the program as you normally would with the interpreter
command: 
</p>
<pre>
  java ReadFile
</pre>
<p>
_______<br>
<a name="TJVM"><sup>1</sup></a> As used on this web site, 
the terms &quot;Java virtual 
machine&quot; or &quot;JVM&quot; mean a virtual machine 
for the Java platform.
</p>
<p>
[<a href="#top">TOP</a>]
</p>
<!-- ================ -->
<!-- End Main Content -->
<!-- ================ -->
<!-- =================== -->
<!-- END OF MAIN CONTENT -->
<!-- =================== -->
<!--stopindex-->
<!-- END CENTRAL COLUMN COMPONENTS -->
</td><td valign="top">
<!-- BEGIN RIGHT COLUMN COMPONENTS -->
<!-- END RIGHT COLUMN COMPONENTS -->
</td></tr>
<!-- BEGIN SPACER ROW -->
<tr><td><img src="/im/a.gif" width="560" height="1" border="0" alt=" " /></td><td><img src="/im/a.gif" width="170" height="1" border="0" alt=" " /></td></tr>
<!-- END SPACER ROW -->
</table>
<!-- END WRAPPER TABLE, 2 COLUMN, MAIN/RIGHT -->
<!-- BEGIN PC1 COMPONENT V.2 -->
<div class="pc1 pc1v2" style="margin:0 10px">
<div class="pc1w1"><div class="pc1w2"><div class="pc1w3 cornerBL"><div class="pc1w4">
<p>Oracle is reviewing the Sun product roadmap and will provide guidance to customers in accordance with Oracle's standard product communication policies. Any resulting features and timing of release of such features as determined by Oracle's review of roadmaps, are at the sole discretion of Oracle. All product roadmap information, whether communicated by Sun Microsystems or by Oracle, does not represent a commitment to deliver any material, code, or functionality, and should not be relied upon in making purchasing decisions. It is intended for information purposes only, and may not be incorporated into any contract.</p>
</div></div></div></div>
</div>
<!-- END PC1 COMPONENT V.2 -->
<!-- BEGIN G9 VARIATION 0 -->
<script language="javascript" type="text/javascript" charset="UTF-8" src="/js/op/oo_engine.js"></script>
<script language="javascript" type="text/javascript" charset="UTF-8" src="/js/op/oo_conf_en-US.js"></script>
<!-- END G9 VARIATION 0 -->
<!-- BEGIN VNV5 FOOTER  -->
<table border="0" cellpadding="0" cellspacing="10" width="100%">
<tr>
<td>
<table border="0" cellpadding="0" cellspacing="0" width="100%" class="vatop">
<tr>
<td colspan="4" valign="top" class="grey3"><img src="/im/a.gif" width="1" height="2" border="0" alt="" /></td></tr>
<tr>
<td><img src="http://developers.sun.com/im/a.gif" width="190" height="1" border="0" alt="" /><br />
<a href="http://www.oracle.com/index.html"><img src="/im/logo_oracle_footer.gif" width="93" height="29" border="0" alt="" vspace="5"/></a></td>
<td width="100%" valign="top"><img src="/im/a.gif" width="350" height="1" border="0" alt="" /><br />
<div class="footer">
<a href="http://developers.sun.com/global/aboutsun.html">About Sun</a> &nbsp;|&nbsp;
<a href="http://developers.sun.com/global/aboutsdn.html">About This Site</a> &nbsp;|&nbsp;
<a href="http://developers.sun.com/global/newsletters.html">Newsletters</a> &nbsp;|&nbsp;
<a href="http://developers.sun.com/global/contact.html">Contact Us</a> &nbsp;|&nbsp;
<a href="http://developers.sun.com/global/employment.html">Employment</a> &nbsp;|&nbsp;
<a href="http://developers.sun.com/global/howtobuy.html">How to Buy</a> &nbsp;|&nbsp;
<a href="http://developers.sun.com/global/licensing.html">Licensing</a> &nbsp;|&nbsp;
<a href="http://developers.sun.com/global/termsofuse.html">Terms of Use</a> &nbsp;|&nbsp;
<a href="http://developers.sun.com/global/privacy.html">Privacy</a> &nbsp;|&nbsp;
<a href="http://developers.sun.com/global/trademarks.html">Trademarks</a>
<br /><span class="sp10">&nbsp;</span><br />
<br /><span class="sp10">&nbsp;</span><br />
<!-- <span id="copyDate" class="cssDate"></span>--> &copy; 2010, Oracle Corporation and/or its affiliates
</div></td>
<td><img src="/im/a.gif" width="40" height="1" border="0" alt="" /></td>
<td valign="top"><div class="footer"><b><a href="http://developers.sun.com/global/aboutsdn.html">A Sun Developer Network Site</a></b></div>
<div class="footer">
<img src="/im/a.gif" width="170" height="1" border="0" alt="" /><br />
Unless otherwise licensed, code in all technical manuals herein (including articles, FAQs, samples) is provided under this <a href="http://developers.sun.com/global/berkeley_license.html">License</a>.
<br /><span class="sp5">&nbsp;</span><br />
<a href="http://developers.sun.com/global/rss_sdn.html"><img src="/im/ic_feed_16x.gif" width="16" height="16" align="top" border="0" alt="XML" /></a>&nbsp;<a href="http://developers.sun.com/global/content_feeds.html">Sun Developer RSS Feeds</a>
</div></td></tr>
<tr><td colspan="4" valign="top" class="grey3"><img src="/im/a.gif" width="1" height="2" border="0" alt="" /></td></tr>
</table>
</td></tr>
</table>
<!-- END VNV5 FOOTER -->
<script language="JavaScript" src="/js/omi/jsc/s_code_remote.js"></script></body>
</html>



